package com.ysx.admin.listener;

import com.alibaba.fastjson.JSON;
import com.ysx.admin.pojo.AdSensitive;
import com.ysx.admin.service.AdSensitiveService;
import com.ysx.admin.service.impl.AdWemediaNewsAutoScanServiceImpl;
import com.ysx.article.feign.ApArticleDtoFeign;
import com.ysx.common.constants.BusinessConstants;
import com.ysx.common.pojo.Result;
import com.ysx.common.utils.GreenImageScan;
import com.ysx.common.utils.GreenTextScan;
import com.ysx.common.utils.SensitiveWordUtil;
import com.ysx.dfs.feign.ParsingPathFeign;
import com.ysx.wemedia.dto.ContentNode;
import com.ysx.wemedia.feign.WeMediaNewsFeign;
import com.ysx.wemedia.pojo.WmNews;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

@Component
@Slf4j
public class VmNewsListener {

    @Autowired
    private KafkaTemplate kafkaTemplate;
    @Autowired//自媒体微服务调用
    private WeMediaNewsFeign weMediaNewsFeign;
    @Autowired//fastDFS路径解析
    private ParsingPathFeign parsingPathFeign;
    @Autowired//保存DTO三个对象
    private ApArticleDtoFeign apArticleDtoFeign;
    @Autowired//文字审核
    private GreenTextScan greenTextScan;
    @Autowired//图片审核
    private GreenImageScan greenImageScan;
    @Autowired
    private AdSensitiveService adSensitiveService;

    @Autowired
    private AdWemediaNewsAutoScanServiceImpl adWemediaNewsAutoScanServiceImpl;//抽取的方法

    @KafkaListener(topics = BusinessConstants.MqConstants.WM_NEWS_TO_ADMIN_MQTOPIC)
    public Result VmNewsAutoListener(ConsumerRecord<String,String> record)throws Exception{
        boolean flag=false;
        String vmNewsId = (String) record.value();
        log.debug("来自自媒体发送的消息队列的值:{}",vmNewsId);
        //根据自媒体id查询自媒体素材
        WmNews wmNews = weMediaNewsFeign.findById(vmNewsId).getData();
        //获取文本 获取图片
        String images = wmNews.getImages();
        String content = wmNews.getContent();
        String title = wmNews.getTitle();
        //调用方法 获取文本字节集合
        List<String> textList=obtainTextListByContentAndTitle(content,title);
        //获取图片字节集合
        List<String> imagesList=obtainImagesListByContentAndImages(content,images);
        //调用dfs-feign接口 解析图片路径
        List<byte[]> imagesByteList = parsingPathFeign.parsingPathByListStr(imagesList);
        //调用审核方法
        String status = checkImageAndText(textList, imagesByteList);
        switch (status) { //修改自媒体状态
            case BusinessConstants.AliYunScanConstants.BLOCK:
                wmNews.setStatus(2);//失败
                weMediaNewsFeign.updateByPrimaryKey(wmNews);
                break;
            case BusinessConstants.AliYunScanConstants.REVIEW:
                wmNews.setStatus(3);//人工
                weMediaNewsFeign.updateByPrimaryKey(wmNews);
                break;
            case BusinessConstants.AliYunScanConstants.PASS:
                //如果有发布时间 那么就说明提交过了
                if (Objects.isNull(wmNews.getPublishTime())) {
                    wmNews.setStatus(8);
                } else {
                    wmNews.setStatus(9);
                    //需要在文章微服务中保存文章
                    flag=true;
                }
                weMediaNewsFeign.updateByPrimaryKey(wmNews);
                break;
        }
        if (flag) {
            //发布文章信息
            adWemediaNewsAutoScanServiceImpl.AdPublishNewsToArticleService(wmNews);
        }
        return null;
    }



    //获取文本集合
    private List<String> obtainTextListByContentAndTitle(String content, String title) {
        //调用工具类 将字符串转成一个对象 ContentNode
        List<ContentNode> contentNodes = JSON.parseArray(content, ContentNode.class);
        //使用Stream流 将符合条件的对象填充
        List<String> textList = contentNodes.stream()
                .filter(ContentNode -> ContentNode.getType().equals("text"))
                .map(ContentNode::getValue)
                .collect(Collectors.toList());
        //判断
        textList.add(title);
        return textList;
    }
    //获取图片集合
    private List<String> obtainImagesListByContentAndImages(String content, String images) {
        List<String> resultList = new ArrayList<String>();
        List<ContentNode> contentNodes = JSON.parseArray(content, ContentNode.class);
        List<String> imageList = contentNodes.stream()
                .filter(ContentNode -> ContentNode.getType().equals("image"))
                .map(ContentNode::getValue)
                .collect(Collectors.toList());
        //调用方法 解析出图片的信息
        List<String> imagesArraysToList = Arrays.asList(images.split(","));
        imageList.addAll(imagesArraysToList);
        //遍历集合 调用fastDFS 进行解析获取List<byte>
        resultList.addAll(imageList);
        resultList.addAll(imagesArraysToList);
        return resultList;
    }

    //审核方法
    private String checkImageAndText(List<String> textList, List<byte[]> imagesByteList) throws Exception {
        String status;
        /*//审核文字
        Map textMap = greenTextScan.greeTextScan(textList);
            status = (String) textMap.get("suggestion");
        if (!"pass".equals(status)) {
            return status;
        }
        //审核图片
        Map imagesMap = greenImageScan.imageScan(imagesByteList);
            status = (String) imagesMap.get("suggestion");
        if (!"pass".equals(status)) {
            return status;
        } TODO 内容审核老是失效 后续修复这个BUG*/
        //审核敏感词汇
        status= checkSensitive(textList);
     return status;
    }

    //审核敏感词汇
    private String checkSensitive(List<String> textList) {
        //内部调用 AdSensitiveService
        List<AdSensitive> list = adSensitiveService.list();
        List<String> collect = list.stream().map(AdSensitive::getSensitives).collect(Collectors.toList());
        //将敏感词集合存入到缓存中 TODO
        SensitiveWordUtil.initMap(collect);
        //遍历text集合 如果有敏感词汇就返回Block
        for (String text : textList) {
            Map<String, Integer> matchWords = SensitiveWordUtil.matchWords(text);
            if (matchWords.size() > 0) {
                //说明有敏感词汇 就报错
                return BusinessConstants.AliYunScanConstants.BLOCK;
            }
        }
        return BusinessConstants.AliYunScanConstants.PASS;
    }

}
